package cn.jiyun.consumer.controller;

import cn.jiyun.consumer.client.UserClient;
import cn.jiyun.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author Fay
 * @date 2022/6/25&12:04
 */

@RestController
@RequestMapping("consumer")
//配置全部类都执行降级
//@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserClient userClient;
    @GetMapping("/findById/{id}")
    //执行降级注解 括号里为去执行的方法 因为降级是controller等待service端响应
    //@HystrixCommand(fallbackMethod = "findByIdFallBack")
    //配置全部类都要降级类的所有方法上都需要加@HystrixCommand注解
    @HystrixCommand
    public User findById(@PathVariable("id") Long id){
        //模拟1失败的情况
//        if (id==1){
//            throw new RuntimeException("太忙了");
//        }
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://user-service/user/findById/" + id;

//        String url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/findById/"+id;
//        String user = restTemplate.getForObject(url, String.class);
        return userClient.findById(id);

    }
//    //降级逻辑
//    public String findByIdFallBack(Long id){
//        return "对不起,网络拥挤";
//    }
//    public String defaultFallback(){
//        return "对不起,网络不可用";
//    }
}
